package edu.gyc.lover.controller;

import edu.gyc.lover.utils.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Controller
@Slf4j
public class UploadController {
    private static List<String> fileNameList = new ArrayList<>();

    public static List<String> getFileNameList() {
        return fileNameList;
    }
/*
    @GetMapping("/upload")
    public String upload() {
        return "upload";
    }
    public static void uploadFile(byte[] file, String filePath, String fileName) throws Exception {
        File targetFile = new File(filePath);
        if(!targetFile.exists()){
            targetFile.mkdirs();
        }
        FileOutputStream out = new FileOutputStream(filePath+fileName);
        out.write(file);
        out.flush();
        out.close();
    }
*

 */
    @PostMapping("/upload")

    public String upload(@RequestParam("file") MultipartFile file,HttpServletRequest request) {
        if (file.isEmpty()) {
            return "上传失败，请选择文件";
        }

        String fileName = file.getOriginalFilename();
        fileNameList.add(fileName);
        String fileContentType=file.getContentType();


        File dest = new File(FileUtil.getImgsPath() + fileName);
        try {
            file.transferTo(dest);
            //log.info("上传成功");
            return "redirect:/";
        } catch (IOException e) {
           // log.error(e.toString(), e);
        }
        return "上传失败！";
    }


}


